#! F:\Python\python.exe
#coding=utf-8

from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler, CGIXMLRPCRequestHandler
from SocketServer import ThreadingMixIn
from skydbobject import *
from sqlalchemy.types import *
import sqlalchemy
import sqlalchemy.orm
import time, threading
import traceback, sys
import pymssql

class SignInfo():
    def __init__(self, nickname = '', account = '', password = '', cellnumber = '', verifycode = ''):
        self.nickname = nickname
        self.account = account
        self.password = password
        self.cellnumber = cellnumber
        self.verifycode = verifycode
        
class ContactScene(object):
        def __init__(self, sceneName='', nameIdx=0, phoneIdx=0, emailIdx=0, addrIdx=0, urlIdx=0, photoIdx=0, remarkIdx=0, imIdx=0, touchFrequency=0):
            self.sceneName = sceneName
            self.nameIdx = nameIdx
            self.phoneIdx = phoneIdx
            self.emailIdx = emailIdx
            self.addrIdx = addrIdx
            self.urlIdx = urlIdx
            self.photoIdx = photoIdx
            self.remarkIdx = remarkIdx
            self.imIdx = imIdx
            self.touchFrequency = touchFrequency

        def __hash__(self):
            _h = 0
            _h = 5 * _h + hash(self.sceneName)
            _h = 5 * _h + hash(self.nameIdx)
            _h = 5 * _h + hash(self.phoneIdx)
            _h = 5 * _h + hash(self.emailIdx)
            _h = 5 * _h + hash(self.addrIdx)
            _h = 5 * _h + hash(self.urlIdx)
            _h = 5 * _h + hash(self.photoIdx)
            _h = 5 * _h + hash(self.remarkIdx)
            _h = 5 * _h + hash(self.imIdx)
            _h = 5 * _h + hash(self.touchFrequency)
            return _h % 0x7fffffff

        def __eq__(self, other):
            if not self.sceneName == other.sceneName:
                return False
            if not self.nameIdx == other.nameIdx:
                return False
            if not self.phoneIdx == other.phoneIdx:
                return False
            if not self.emailIdx == other.emailIdx:
                return False
            if not self.addrIdx == other.addrIdx:
                return False
            if not self.urlIdx == other.urlIdx:
                return False
            if not self.photoIdx == other.photoIdx:
                return False
            if not self.remarkIdx == other.remarkIdx:
                return False
            if not self.imIdx == other.imIdx:
                return False
            if not self.touchFrequency == other.touchFrequency:
                return False
            return True

        def __str__(self):
            return "sceneName=%(sceneName)s"\
                   "nameIdx=%(nameIdx)d"\
                   "phoneIdx=%(phoneIdx)d"\
                   "emailIdx=%(emailIdx)d"\
                   "addrIdx=%(addrIdx)d"\
                   "urlIdx=%(urlIdx)d"\
                   "photoIdx=%(phoneIdx)d"\
                   "remarkIdx=%(remarkIdx)d"\
                   "imIdx=%(imIdx)d"\
                   "touchFrequency=%(touchFrequency)d"\
                   %{"sceneName":self.sceneName
                     , "nameIdx":self.nameIdx
                     , "phoneIdx":self.phoneIdx
                     , "emailIdx":self.emailIdx
                     , "addrIdx":self.addrIdx
                     , "urlIdx":self.urlIdx
                     , "photoIdx":self.photoIdx
                     , "remarkIdx":self.remarkIdx
                     , "imIdx":self.imIdx
                     , "touchFrequency":self.touchFrequency
                     }
        
        def toList(self):                                               
            scene = []
            scene.append(self.sceneName)
            scene.append(self.nameIdx)
            scene.append(self.phoneIdx)
            scene.append(self.emailIdx)
            scene.append(self.addrIdx)
            scene.append(self.urlIdx)
            scene.append(self.photoIdx)
            scene.append(self.remarkIdx)
            scene.append(self.imIdx)
            scene.append(self.touchFrequency)
            return scene

        __repr__ = __str__
        
class ContactItem(object):
        def __init__(self, id='', nameSeq=None, phoneSeq=None, emailSeq=None, addrSeq=None, urlSeq=None, photoSeq=None, remarkSeq=None, imSeq=None, sceneSeq=None, defaultScene=0, lastModified=0):
            self.id = id
            self.nameSeq = nameSeq
            self.phoneSeq = phoneSeq
            self.emailSeq = emailSeq
            self.addrSeq = addrSeq
            self.urlSeq = urlSeq
            self.photoSeq = photoSeq
            self.remarkSeq = remarkSeq
            self.imSeq = imSeq
            self.sceneSeq = sceneSeq
            self.defaultScene = defaultScene
            self.lastModified = lastModified

        def __hash__(self):
            _h = 0
            _h = 5 * _h + hash(self.id)
            if self.nameSeq:
                for _i0 in self.nameSeq:
                    _h = 5 * _h + hash(_i0)
            if self.phoneSeq:
                for _i1 in self.phoneSeq:
                    _h = 5 * _h + hash(_i1)
            if self.emailSeq:
                for _i2 in self.emailSeq:
                    _h = 5 * _h + hash(_i2)
            if self.addrSeq:
                for _i3 in self.addrSeq:
                    _h = 5 * _h + hash(_i3)
            if self.urlSeq:
                for _i4 in self.urlSeq:
                    _h = 5 * _h + hash(_i4)
            if self.photoSeq:
                for _i5 in self.photoSeq:
                    _h = 5 * _h + hash(_i5)
            if self.remarkSeq:
                for _i6 in self.remarkSeq:
                    _h = 5 * _h + hash(_i6)
            if self.imSeq:
                for _i7 in self.imSeq:
                    _h = 5 * _h + hash(_i7)
            if self.sceneSeq:
                for _i8 in self.sceneSeq:
                    _h = 5 * _h + hash(_i8)
            _h = 5 * _h + hash(self.defaultScene)
            _h = 5 * _h + hash(self.lastModified)
            return _h % 0x7fffffff

        def __eq__(self, other):
            if not self.id == other.id:
                return False
            if not self.nameSeq == other.nameSeq:
                return False
            if not self.phoneSeq == other.phoneSeq:
                return False
            if not self.emailSeq == other.emailSeq:
                return False
            if not self.addrSeq == other.addrSeq:
                return False
            if not self.urlSeq == other.urlSeq:
                return False
            if not self.photoSeq == other.photoSeq:
                return False
            if not self.remarkSeq == other.remarkSeq:
                return False
            if not self.imSeq == other.imSeq:
                return False
            if not self.sceneSeq == other.sceneSeq:
                return False
            if not self.defaultScene == other.defaultScene:
                return False
            if not self.lastModified == other.lastModified:
                return False
            return True

        def __str__(self):
            return "id=%(id)s"\
                   "nameSeq=%(nameSeq)s"\
                   "phoneSeq=%(phoneSeq)s"\
                   "emailSeq=%(emailSeq)s"\
                   "addrSeq=%(addrSeq)s"\
                   "urlSeq=%(urlSeq)s"\
                   "photoSeq=%(photoSeq)s"\
                   "remarkSeq=%(remarkSeq)s"\
                   "imSeq=%(imSeq)s"\
                   "sceneSeq=%(sceneSeq)s"\
                   "defaultScene=%(defaultScene)d"\
                   "lastModified=%(lastModified)d"\
                   %{"id":self.id
                     , "nameSeq":self.nameSeq
                     , "phoneSeq":self.phoneSeq
                     , "emailSeq":self.emailSeq
                     , "addrSeq":self.addrSeq
                     , "urlSeq":self.urlSeq
                     , "photoSeq":self.photoSeq
                     , "remarkSeq":self.remarkSeq
                     , "imSeq":self.imSeq
                     , "sceneSeq":self.sceneSeq
                     , "defaultScene":self.defaultScene
                     , "lastModified":self.lastModified
                     }

        __repr__ = __str__
        
        @staticmethod
        def seqToString(seq):
            seqStr = "["
            for index, item in enumerate(seq):
                seqStr += item
                if index < (len(seq)-1):
                    seqStr += ", "
            seqStr = "]" 
            return seqStr
        
        def toList(self):   
            resultList = []
            resultList.append(self.id)
            print "nameSeq", self.nameSeq
            print "phoneSeq", self.phoneSeq
            print "emailSeq", self.emailSeq
            print "addrSeq", self.addrSeq
            print "urlSeq", self.urlSeq
            print "photoSeq", self.photoSeq
            print "remarkSeq", self.remarkSeq
            print "imSeq", self.imSeq
            print "sceneSeq", self.sceneSeq
            if self.nameSeq is None:
                resultList.append('')
            else:
                resultList.append(self.nameSeq)
            
            if self.phoneSeq is None:
                resultList.append('')
            else:
                resultList.append(self.phoneSeq)
            if self.emailSeq is None:
                resultList.append('')
            else:
                resultList.append(self.emailSeq)
            if self.addrSeq is None:
                resultList.append('')
            else:
                resultList.append(self.addrSeq)
            if self.urlSeq is None:
                resultList.append('')
            else:
                resultList.append(self.urlSeq)
            if self.photoSeq is None:
                resultList.append('')
            else:
                resultList.append(self.photoSeq)#photo how to send to client?                       
            if self.remarkSeq is None:
                resultList.append('')
            else:
                resultList.append(self.remarkSeq)            
            if self.imSeq is None:
                resultList.append('')
            else:
                resultList.append(self.imSeq)
            if self.sceneSeq is None:
                resultList.append('')
            else:
                resultList.append(self.sceneSeq)
            if self.defaultScene is None:
                resultList.append('')
            else:
                resultList.append(self.defaultScene)
            if self.lastModified is None:
                resultList.append('')
            else:
                resultList.append(self.lastModified)
            return resultList

class contactField():
    def __init__(self, fieldID = 0):
        self.fieldID = fieldID
        self.attrValueArray = []

class MssqlMgr():
    def __init__(self, host, db, user, pwd ):          
        self.con = pymssql.connect(host=host,user=user,password=pwd,database=db)
        self.cur = self.con.cursor()

    def getAllValues(self, query):
        self.cur.execute(query)    
        return self.cur.fetchall()

class CAssistant():
    def __init__(self, id):
        """id is skyWalker's account."""
        self.strAccount_ = id
        
    def getUserInfo (self, iPageNum, iPageSize, strWhere, typeClass):
        """ Get user informations from DataBase which is condition with strWhere.
        
        in parameters description:
        iPageNum 
          pagination number.
        iPageSize
          how many users on one page.
        strWhere
          the condition with user information.
          must like "tmpTbl.nickName LIKE 'x%'"
        
        out parameters description:
        iTotalSize
          total number of one user's friends.
        records
          all user informations in data base.
          it are many lists.
        """
        #dbPageNum = iPageNum + 1
        #begin get userID(integer) by accounts in database
#        sqlalchemy.create_engine(g_DBConnectionStr)
        session = sqlalchemy.orm.create_session()
        queryObj = session.query(skyUserInfoObj).filter(skyUserInfoObj.c.accounts == self.strAccount_).first()
        userID = queryObj.userID
        #end get userID(integer) by accounts in database
        strDBSP = "exec GetPagingData\
                @tablename = '%(tablename)s',\
                @fieldlist = %(fieldlist)s,\
                @orderfield = %(orderfield)s,\
                @orderfield2 = %(orderfield2)s,\
                @keyfield = %(keyfield)s,\
                @pageindex =%(pageindex)d,\
                @pagesize = %(pagesize)d,\
                @strwhere = '%(strwhere)s',\
                @ordertype = %(ordertype)d,\
                @iscount = %(iscount)d"
        if 1 == typeClass :
            tablename = "(select userID,accounts,password,nickName,email,address,myUrl,myPhoto,imTool,sceneID,totalFrequency,remark,modifyTime,searchmsg from LocalUserInfo where skyUserID = %(skyUserID)d union select userID,accounts,password,nickName,email,address,myUrl,myPhoto,imTool,sceneID,totalFrequency,remark,modifyTime,searchmsg from skyUserInfo where userID in (select friendID from skyUserRelation where userID = %(skyUserID)d )) as tmpTbl " %{'skyUserID' : userID}
            if strWhere != "" :
                strWhere += " and userID <> %(myUserID)d " %{'myUserID' : userID}
            else:
                strWhere += "  userID <> %(myUserID)d " %{'myUserID' : userID}
        elif 0 == typeClass:
            tablename = "skyUserInfo as tmpTbl "
            if strWhere != "" :
                strWhere += " and userID not in \
                (select friendID from skyUserInfo, skyUserRelation  \
                where skyUserInfo.userID = %(myUserID)d and skyUserInfo.userID = skyUserRelation.userID) \
                and userID <> %(myUserID)d " %{'myUserID' : userID}
            else:
                strWhere += " userID not in \
                (select friendID from skyUserInfo, skyUserRelation  \
                where skyUserInfo.userID = %(myUserID)d and skyUserInfo.userID = skyUserRelation.userID) \
                and userID <> %(myUserID)d " %{'myUserID' : userID}
        isCount = 1
        strDBSPTmp = strDBSP % {'tablename' : tablename, 
                                  'fieldlist' : "'*'", 
                                  'orderfield' : "'[userID] '" , 
                                  'orderfield2' : "'[totalFrequency]'", 
                                  'keyfield' : "'[userID]'", 
                                  'pageindex' : iPageNum, 
                                  'pagesize' : iPageSize, 
                                  'strwhere' : " " + strWhere, 
                                  'ordertype' : 1, 
                                  'iscount': isCount}
        mssqlMgr = MssqlMgr(g_host, g_db, g_user, g_pwd)
        totalSize = mssqlMgr.getAllValues(strDBSPTmp)[0][0]
        isCount = 0
        strDBSPTmp1 = strDBSP % {'tablename' : tablename, 
                          'fieldlist' : "'*'", 
                          'orderfield' : "'[userID] '" , 
                          'orderfield2' : "'[totalFrequency]'", 
                          'keyfield' : "'[userID]'", 
                          'pageindex' : iPageNum, 
                          'pagesize' : iPageSize, 
                          'strwhere' : " " + strWhere, 
                          'ordertype' : 1, 
                          'iscount': isCount}
        recordList = mssqlMgr.getAllValues(strDBSPTmp1)
        return totalSize, recordList

class SkyPimManager():
    def __init__(self, id):
        self.id_ = id 
        self.session = None  
        self.transaction = None 
        self.timer = None       
      
    def find(self, context, pageNum, pageSize, typeClass):
        print "\nfind()\n"
        if context != "" :
            if typeClass == 1:
                strWhere = " tmpTbl.searchmsg LIKE ''%%" + context + "%%'' "
            else:
                strWhere = " tmpTbl.nickName LIKE ''%%" + context + "%%'' "
        else:
            strWhere = ""
        assistant = CAssistant(self.id_)
        totalSize, recordList = assistant.getUserInfo(pageNum, pageSize, strWhere, typeClass)
        
        
        #print len(recordList)
        print totalSize
        print "__LINE NUMBER 282"
        session = sqlalchemy.orm.create_session()
        contactList = []
        print recordList
        for friend in recordList:
            item = ContactItem(id=friend[1], 
                                   nameSeq=[], 
                                   phoneSeq=[], 
                                   emailSeq=[], 
                                   addrSeq=[], 
                                   urlSeq=[], 
                                   photoSeq=[], #friend[7]
                                   remarkSeq=[], 
                                   imSeq=[], 
                                   sceneSeq=[], 
                                   defaultScene=friend[9], 
                                   lastModified=friend[12])
            
            if friend[3] != "":
                item.nameSeq.append(friend[3])
            if friend[4] != "":
                item.emailSeq.append(friend[4])
            if friend[5] != "":
                item.addrSeq.append(friend[5])
            if friend[6] != "":
                item.urlSeq.append(friend[6])
            if friend[7] != None:
                item.photoSeq.append(friend[7])
            if friend[11] != "":
                item.remarkSeq.append(friend[11])
            if friend[8] != "":
                item.imSeq.append(friend[8])
            #print "__LINE NUMBER 298 and friend =", friend
            sceneList = session.query(skySceneObj).filter_by(userID = friend[0]).all()
            for scene in sceneList :
                scenseItem = ContactScene()
                scenseItem.sceneName = scene.sceneName
                scenseItem.touchFrequency = scene.touchFrequency
                
                userPhone = session.query(skyUserPhoneObj).filter_by(userID = friend[0], phoneIndex = scene.phoneIndex).first()
                if userPhone != None:
                    if userPhone.phoneNum not in item.phoneSeq:
                        item.phoneSeq.append(userPhone.phoneNum)
                    phoneIndex = item.phoneSeq.index(userPhone.phoneNum)
                    scenseItem.phoneIdx = phoneIndex
                    item.sceneSeq.append(scenseItem.toList())
                else:
                    error  = "phoneNum of the table(skySceneObj) cannot find in the table(skyUserPhoneObj)"
                    raise error
                    
            #print '\n'.join(item.toList())
            contactList.append(item.toList())
        #print "__LINE NUMBER 314 and", len( contactList )   
        print "contactList = \n { \n", contactList, "\n }"
        print "totalSize = ", totalSize
        print "len(contactList) = " , len(contactList), "\n"
        print "\nEnd find()\n"
        return totalSize, contactList

    def delete(self, idList):
        print "\ndelete()\n"
        session = sqlalchemy.orm.create_session()
        transaction=session.create_transaction()
        try:
            user = session.query(skyUserInfoObj).filter_by(accounts = self.id_).first()
            for idIndex in range(len(idList)):
                if(idList[idIndex][0] == '_'):
                    localFriend = session.query(LocalUserInfoObj).filter_by(accounts = idList[idIndex], skyUserID = user.userID).first()
                    if localFriend != None:
                        localFriend_bak1 = LocalUserInfoObj_bak1(localFriend)
                        session.query(LocalUserInfoObj_bak1)
                        session.save(localFriend_bak1)
                        session.flush()
                        session.query(LocalUserInfoObj)
                        session.delete(localFriend)
                        session.flush()
                        localFriendSceneList = session.query(skySceneObj).filter_by(userID = localFriend.userID).all() 
                        for localFriendScene in localFriendSceneList :
                            localFriendScene_bak1 = skySceneObj_bak1(localFriendScene)
                            session.query(skySceneObj_bak1)
                            session.save(localFriendScene_bak1)
                            session.flush()
                            session.query(skySceneObj)
                            session.delete(localFriendScene)
                        userPhoneList = session.query(skyUserPhoneObj).filter_by(userID = localFriend.userID).all()
                        for userPhone in userPhoneList :
                            userPhone_bak1 = skyUserPhoneObj_bak1(userPhone)
                            session.query(skyUserPhoneObj_bak1)
                            session.save(userPhone_bak1)
                            session.flush()
                            session.query(skyUserPhoneObj)
                            session.delete(userPhone)
                
                else:
                    user = session.query(skyUserInfoObj).filter_by(accounts = self.id_).first()
                    friend = session.query(skyUserInfoObj).filter_by(accounts = idList[idIndex]).first()
                    if friend != None:
                        relation =  session.query(skyUserRelationObj).filter_by(userID = user.userID, friendID = friend.userID).first()
                        if relation != None:
                            session.delete(relation)
                    
            transaction.commit()
        except:
            transaction.rollback()
            raise
        
        print "\nEnd delete()\n"
        return True

    def add(self, contactList):
        print "\nadd()\n"
        print locals()
        session = sqlalchemy.orm.create_session() 
        transaction=session.create_transaction()
        try:
            user = session.query(skyUserInfoObj).filter_by(accounts = self.id_).first()
            for contactItem in contactList:
                sceneNameList = []
                for sceneItem in contactItem.sceneSeq:
                    sceneNameList.append(sceneItem.sceneName)
                for sceneNameItem in sceneNameList:
                    count = sceneNameList.count(sceneNameItem)
                    if count > 1:
                        error = "sceneName repeat"
                        raise error
                    
                if(contactItem.id[0] == '_'):
                    if len(contactItem.sceneSeq) == 0 or len(contactItem.phoneSeq) == 0:
                        error = "localFriend  have not scene or phone"
                        raise error
                    
                    localFriendItem = session.query(LocalUserInfoObj).filter_by(accounts = contactItem.id, skyUserID = user.userID).first()
                    if localFriendItem != None:
                        error = "localFriend is in the table(LocalUserInfoObj)"
                        raise error
                    
                    localFriend = LocalUserInfoObj()
                    localFriend.skyUserID = user.userID
                    localFriend.accounts = contactItem.id
                    localFriend.searchmsg = ""
                    if len(contactItem.nameSeq) != 0:
                        localFriend.nickName = contactItem.nameSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.nickName
                    else:
                        localFriend.nickName = ""
                    if len(contactItem.emailSeq) != 0:
                        localFriend.email = contactItem.emailSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.email
                    else:
                        localFriend.email = ""
                    if len(contactItem.addrSeq) != 0:
                        localFriend.address = contactItem.addrSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.address
                    else:
                        localFriend.address = ""
                    if len(contactItem.urlSeq) != 0:
                        localFriend.myUrl = contactItem.urlSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.myUrl
                    else:
                        localFriend.myUrl = ""
                    if len(contactItem.photoSeq) != 0:
                        localFriend.myPhoto = contactItem.photoSeq[0]
                    else:
                        localFriend.myPhoto = None
                    if len(contactItem.imSeq) != 0:
                        localFriend.imTool = contactItem.imSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.imTool
                    else:
                        localFriend.imTool = ""
                    if len(contactItem.remarkSeq) != 0:
                        localFriend.remark = contactItem.remarkSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.remark
                    else:
                        localFriend.remark = ""
                        
                    for phoneNum in contactItem.phoneSeq:
                        localFriend.searchmsg = localFriend.searchmsg + "-" + str(phoneNum)
                        
                    localFriend.sceneID = contactItem.defaultScene
                    localFriend.totalFrequency = 0
                    localFriend.password = ""
                    localFriend.modifyTime = int(time.time())
                    print  localFriend
                    session.query(LocalUserInfoObj)
                    session.save(localFriend)
                    session.flush()
                
                    localFriend = session.query(LocalUserInfoObj).filter_by(accounts = contactItem.id, skyUserID = user.userID).first()
                    for phoneIndex in range(len(contactItem.phoneSeq)):
                        localFriendPhone = skyUserPhoneObj()
                        localFriendPhone.userID = localFriend.userID
                        localFriendPhone.phoneIndex = phoneIndex
                        localFriendPhone.phoneNum = contactItem.phoneSeq[phoneIndex]
                        session.query(skyUserPhoneObj)
                        session.save(localFriendPhone)
                    for sceneIndex in range(len(contactItem.sceneSeq)):
                        if contactItem.sceneSeq[sceneIndex].phoneIdx < len(contactItem.phoneSeq):
                            localFriendScene = skySceneObj()
                            localFriendScene.userID = localFriend.userID
                            localFriendScene.sceneID = sceneIndex
                            localFriendScene.phoneIndex = contactItem.sceneSeq[sceneIndex].phoneIdx
                            localFriendScene.sceneName = contactItem.sceneSeq[sceneIndex].sceneName
                            localFriendScene.touchFrequency = 0
                            session.query(skySceneObj)
                            session.save(localFriendScene)  
                        else:
                            error = "phoneNum is not in skyUserPhoneObj"
                            raise error
                
                else:
                    friend = session.query(skyUserInfoObj).filter_by(accounts = contactItem.id).first()
                    if friend != None:
                        relation = skyUserRelationObj()
                        relation.userID = user.userID
                        relation.friendID = friend.userID
                        if len(contactItem.nameSeq) == 0:
                            relation.friendNickName = friend.nickName
                        else:
                            relation.friendNickName = contactItem.nameSeq[0]
                        relation.friendSceneID = contactItem.defaultScene
                        session.query(skyUserRelationObj)
                        session.save(relation)  
                    else:
                        error = "friend is not in the table(skyUserInfoObj)"
                        print locals()
                        raise error
                        
            transaction.commit()
        except:
            transaction.rollback()
            raise
         
        print "\nEnd add()\n"   
        return True

    def update(self, contactList):
        print "\nupdate()\n"
        print contactList
        session = sqlalchemy.orm.create_session() 
        #session._set_echo_uow(value=True)
        transaction=session.create_transaction()
        try:
            user = session.query(skyUserInfoObj).filter_by(accounts = self.id_).first()
            for contactItem in contactList:
                sceneNameList = []
                for sceneItem in contactItem.sceneSeq:
                    sceneNameList.append(sceneItem.sceneName)
                for sceneNameItem in sceneNameList:
                    count = sceneNameList.count(sceneNameItem)
                    if count > 1:
                        error = "sceneName repeat"
                        raise error
 
                if(contactItem.id[0] == '_'):
                    if len(contactItem.sceneSeq) == 0 or len(contactItem.phoneSeq) == 0:
                        error = "localFriend  have not scene or phone"
                        raise error
                
                    localFriend = session.query(LocalUserInfoObj).filter_by(accounts = contactItem.id, skyUserID = user.userID).first()
                    if localFriend == None:
                        error = "localFriend is not in the table(LocalUserInfoObj)"
                        raise error
                
                    localFriend.accounts = contactItem.id
                    localFriend.searchmsg = ""
                    if len(contactItem.nameSeq) != 0:
                        localFriend.nickName = contactItem.nameSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.nickName
                    else:
                        localFriend.nickName = ""
                    if len(contactItem.emailSeq) != 0:
                        localFriend.email = contactItem.emailSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.email
                    else:
                        localFriend.email = ""
                    if len(contactItem.addrSeq) != 0:
                        localFriend.address = contactItem.addrSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.address
                    else:
                        localFriend.address = ""
                    if len(contactItem.urlSeq) != 0:
                        localFriend.myUrl = contactItem.urlSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.myUrl
                    else:
                        localFriend.myUrl = ""
                    if len(contactItem.photoSeq) != 0:
                        localFriend.myPhoto = contactItem.photoSeq[0]
                    else:
                        localFriend.myPhoto = None
                    if len(contactItem.imSeq) != 0:
                        localFriend.imTool = contactItem.imSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.imTool
                    else:
                        localFriend.imTool = ""
                    if len(contactItem.remarkSeq) != 0:
                        localFriend.remark = contactItem.remarkSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.remark
                    else:
                        localFriend.remark = ""
                    
                    for phoneNum in contactItem.phoneSeq:
                        localFriend.searchmsg = localFriend.searchmsg + "-" + phoneNum
                        
                    localFriend.modifyTime = int(time.time())
                    localFriend.sceneID = contactItem.defaultScene
                    session.save(localFriend)
                
                    sceneMap = {}
                    localFriendSceneList = session.query(skySceneObj).filter_by(userID = localFriend.userID).all()
                    for localFriendScene in localFriendSceneList :
                        sceneMap[localFriendScene.sceneName] = localFriendScene.touchFrequency
                        session.delete(localFriendScene)
                        session.flush()
                    userPhoneList = session.query(skyUserPhoneObj).filter_by(userID = localFriend.userID).all() 
                    for userPhone in userPhoneList :
                        session.delete(userPhone)
                        session.flush()

                    for phoneIndex in range(len(contactItem.phoneSeq)):
                        localFriendPhone = skyUserPhoneObj()
                        localFriendPhone.userID = localFriend.userID
                        localFriendPhone.phoneIndex = phoneIndex
                        localFriendPhone.phoneNum = contactItem.phoneSeq[phoneIndex]
                        session.query(skyUserPhoneObj)
                        session.save(localFriendPhone)
                    for sceneIndex in range(len(contactItem.sceneSeq)):
                        if contactItem.sceneSeq[sceneIndex].phoneIdx < len(contactItem.phoneSeq):
                            localFriendScene = skySceneObj()
                            localFriendScene.userID = localFriend.userID
                            localFriendScene.sceneID = sceneIndex
                            localFriendScene.phoneIndex = contactItem.sceneSeq[sceneIndex].phoneIdx
                            localFriendScene.sceneName = contactItem.sceneSeq[sceneIndex].sceneName
                            localFriendScene.touchFrequency = sceneMap.get(localFriendScene.sceneName, 0)
                            session.query(skySceneObj)
                            session.save(localFriendScene)
                        else:
                            error = "phoneNum is not in skyUserPhoneObj"
                            raise error
                            
                
                else:
                    friend = session.query(skyUserInfoObj).filter_by(accounts = contactItem.id).first()
                    relation =  session.query(skyUserRelationObj).filter_by(userID = user.userID, friendID = friend.userID).first()
                    relation.friendNickName = contactItem.nameSeq[0]
                    relation.friendSceneID = contactItem.defaultScene
                    session.save(relation)
                    
            transaction.commit()
        except:
            transaction.rollback()
            raise
            
        print "\nEnd update()\n"
        return True

    def size(self):
        return 0

    def lastModified(self):
        print "\nlastModified()\n"
        session = sqlalchemy.orm.create_session() 
        user = session.query(skyUserInfoObj).filter_by(accounts = self.id_).first()
        if user != None :
            return user.modifyTime
        else :
            return 0

    def getInfo(self):
        print "\ngetInfo()\n"
        session = sqlalchemy.orm.create_session()
        userInfo = session.query(skyUserInfoObj).filter_by(accounts = self.id_).first()
        if userInfo != None :
            contact = ContactItem(id = userInfo.accounts, 
                                    nameSeq = [], 
                                    phoneSeq = [], 
                                    emailSeq = [], 
                                    addrSeq = [], 
                                    urlSeq = [], 
                                    photoSeq = [], 
                                    remarkSeq = [], 
                                    imSeq = [], 
                                    sceneSeq = [], 
                                    defaultScene = userInfo.sceneID, 
                                    lastModified = userInfo.modifyTime)
                                    
            if userInfo.nickName != "":
                contact.nameSeq.append(userInfo.nickName)   
            if userInfo.email != "":
                contact.emailSeq.append(userInfo.email)
            if userInfo.address != "":
                contact.addrSeq.append(userInfo.address)
            if userInfo.myUrl != "":
                contact.urlSeq.append(userInfo.myUrl)
            if userInfo.myPhoto != None:
                contact.photoSeq.append(userInfo.myPhoto)
            if userInfo.remark != "":
                contact.remarkSeq.append(userInfo.remark)
            if userInfo.imTool != "":
                contact.imSeq.append(userInfo.imTool)
            
            sceneList = session.query(skySceneObj).filter_by(userID = userInfo.userID).all()
            for sceneItem in sceneList :
                contactScene = ContactScene()
                contactScene.sceneName = sceneItem.sceneName
                contactScene.touchFrequency = sceneItem.touchFrequency
                userPhone = session.query(skyUserPhoneObj).filter_by(userID = userInfo.userID, phoneIndex = sceneItem.phoneIndex).first()
                if userPhone != None:
                    if userPhone.phoneNum not in contact.phoneSeq:
                        contact.phoneSeq.append(userPhone.phoneNum)
                    phoneIndex = contact.phoneSeq.index(userPhone.phoneNum)
                    contactScene.phoneIdx = phoneIndex
                    contact.sceneSeq.append(contactScene.toList())
                else:
                    error = "phoneNum of the table(skySceneObj) cannot find in the table(skyUserPhoneObj)"
                    raise error
        else:
            error = "user is not in the table(skyUserInfoObj)"
            raise error
        
        print "\nEnd getInfo()\n"
        return True, contact.toList()

    def setInfo(self, contact):
        print "\nsetInfo()\n"
        sceneNameList = []
        for sceneItem in contact.sceneSeq:
            sceneNameList.append(sceneItem.sceneName)
        for sceneNameItem in sceneNameList:
            count = sceneNameList.count(sceneNameItem)
            if count > 1:
                error = "sceneName repeat"
                raise error
            
        session = sqlalchemy.orm.create_session()
        transaction=session.create_transaction()
        try:
            userInfo = session.query(skyUserInfoObj).filter_by(accounts = self.id_).first()
            if userInfo != None :
                #userInfo.password = contact.password
                userInfo.searchmsg = ""
                if len(contact.nameSeq) != 0:
                    userInfo.nickName = contact.nameSeq[0]
                    userInfo.searchmsg = userInfo.searchmsg + "-" + userInfo.nickName
                else:
                    userInfo.nickName = ""
                if len(contact.emailSeq) != 0:
                    userInfo.email = contact.emailSeq[0]
                    userInfo.searchmsg = userInfo.searchmsg + "-" + userInfo.email
                else:
                    userInfo.email = ""
                if len(contact.addrSeq) != 0:
                    userInfo.address = contact.addrSeq[0]
                    userInfo.searchmsg = userInfo.searchmsg + "-" + userInfo.address
                else:
                    userInfo.address = ""
                if len(contact.urlSeq) != 0:
                    userInfo.myUrl = contact.urlSeq[0]
                    userInfo.searchmsg = userInfo.searchmsg + "-" + userInfo.myUrl
                else:
                    userInfo.myUrl = ""
                if len(contact.photoSeq) != 0:
                    userInfo.myPhoto = contact.photoSeq[0]
                else:
                    userInfo.myPhoto = None
                if len(contact.imSeq) != 0:
                    userInfo.imTool = contact.imSeq[0]
                    userInfo.searchmsg = userInfo.searchmsg + "-" + userInfo.imTool
                else:
                    userInfo.imTool = ""
                if len(contact.remarkSeq) != 0:
                    userInfo.remark = contact.remarkSeq[0]
                    userInfo.searchmsg = userInfo.searchmsg + "-" + userInfo.remark
                else:
                    userInfo.remark = ""
                
                for phoneNum in contact.phoneSeq:
                    userInfo.searchmsg = userInfo.searchmsg + "-" + str(phoneNum)
                        
                userInfo.sceneID = contact.defaultScene
                userInfo.modifyTime = int(time.time())
                session.save(userInfo)
            
                sceneMap = {}
                userSceneList = session.query(skySceneObj).filter_by(userID = userInfo.userID).all() 
                for userScene in userSceneList :
                    sceneMap[userScene.sceneName] = userScene.touchFrequency
                    session.delete(userScene)
                    session.flush()

                userPhoneList = session.query(skyUserPhoneObj).filter_by(userID = userInfo.userID).all() 
                for userPhone in userPhoneList :
                    session.delete(userPhone)
                    session.flush()
                        
                for phoneIndex in range(len(contact.phoneSeq)):
                    userPhone = skyUserPhoneObj()
                    userPhone.userID = userInfo.userID
                    userPhone.phoneIndex = phoneIndex
                    userPhone.phoneNum = contact.phoneSeq[phoneIndex]
                    session.query(skyUserPhoneObj)
                    session.save(userPhone)
                    
                for sceneIndex in range(len(contact.sceneSeq)):
                    if contact.sceneSeq[sceneIndex].phoneIdx < len(contact.phoneSeq):
                        userScene = skySceneObj()
                        userScene.userID = userInfo.userID
                        userScene.sceneID = sceneIndex
                        userScene.phoneIndex = contact.sceneSeq[sceneIndex].phoneIdx
                        userScene.sceneName = contact.sceneSeq[sceneIndex].sceneName
                        userScene.touchFrequency = sceneMap.get(userScene.sceneName, 0)
                        session.query(skySceneObj)
                        session.save(userScene)
                    else:
                        error = "phoneNum is not in skyUserPhoneObj"
                        raise error
            else:
                error = "user is not in the table(skyUserInfoObj)"
                raise error
                
            transaction.commit()
        except:
            transaction.rollback()
            raise
        
        print "\nEnd setInfo()\n"
        return True
    
    def incrementFrequency(self, id, sceneIdx, ip):
        print "\incrementFrequency()\n"
        session = sqlalchemy.orm.create_session()
        transaction=session.create_transaction()
        try:
            if(id[0] == '_'):
                userInfo = session.query(skyUserInfoObj).filter_by(accounts = self.id_).first()
                localFriendInfo = session.query(LocalUserInfoObj).filter_by(accounts = id, skyUserID = userInfo.userID).first()
                if localFriendInfo == None:
                    error = "localFriend is not in the table(LocalUserInfoObj)"
                    raise error
                localFriendInfo.totalFrequency = localFriendInfo.totalFrequency + 1
                session.save(localFriendInfo)
                
                sceneItem = session.query(skySceneObj).filter_by(userID = localFriendInfo.userID, sceneID = sceneIdx).first()
                if sceneItem == None:
                    error = "scene is not in the table(skySceneObj)"
                    raise error
                sceneItem.touchFrequency = sceneItem.touchFrequency + 1
                session.save(sceneItem)
                
            else:    
                friendInfo = session.query(skyUserInfoObj).filter_by(accounts = id).first()
                if friendInfo == None:
                    error = "user is not in the table(skyUserInfoObj)"
                    raise error
                friendInfo.totalFrequency = friendInfo.totalFrequency + 1
                session.save(friendInfo)
            
                sceneItem = session.query(skySceneObj).filter_by(userID = friendInfo.userID, sceneID = sceneIdx).first()
                if sceneItem == None:
                    error = "scene is not in the table(skySceneObj)"
                    raise error
                sceneItem.touchFrequency = sceneItem.touchFrequency + 1
                session.save(sceneItem)
                
            VOIPItem = session.query(VOIPInfoObj).filter_by(voip = ip).first()
            VOIPItem.touchFrequency = VOIPItem.touchFrequency + 1
            session.save(VOIPItem)
            
            UserVOIP = session.query(skyUserVOIPObj).filter_by(userID = userInfo.userID, voipIndex = VOIPItem.voipIndex).first()
            UserVOIP.touchFrequency = UserVOIP.touchFrequency + 1
            session.save(UserVOIP)
            
            transaction.commit()
        except:
            transaction.rollback()
            raise
            
        print "\nEnd incrementFrequency()\n"
        return True
    
    def getVOIP(self, callPhone):
        ipList = []
        session = sqlalchemy.orm.create_session()
        userInfo = session.query(skyUserInfoObj).filter_by(accounts = self.id_).first()
        userPhoneList = session.query(skyUserPhoneObj).filter_by(userID = userInfo.userID).all()
        if len(userPhoneList) == 0:
            error = "user is not in the table(skyUserInfoObj)"
            raise error
            
        localPhone = userPhoneList[0].phoneNum

        localPhoneSeg = localPhone[0:7]
        localPhoneInfo = session.query(phoneSegObj).filter_by(phoneSeg = localPhoneSeg).first()
        localPhoneCity = localPhoneInfo.cityID
        localPhoneProvider = localPhoneInfo.phoneProvider
             
        callPhoneSeg = ''
        callPhoneCity = 0
        try:
            if callPhone[0:1] != '0' and len(callPhone) == 11:
                callPhoneSeg = callPhone[0:7]
                callPhoneInfo = session.query(phoneSegObj).filter_by(phoneSeg = callPhoneSeg).first()
                callPhoneCity = callPhoneInfo.cityID
            elif callPhone[1:2] == '1' and callPhone.count() == 11:
                callPhoneSeg = callPhone[0:3]
                callPhoneInfo = session.query(phoneSegObj).filter_by(phoneSeg = callPhoneSeg).first()
                callPhoneCity = callPhoneInfo.cityID
            elif callPhone[1:2] == '2' and callPhone.count() == 11:
                callPhoneSeg = callPhone[0:3]
                callPhoneInfo = session.query(phoneSegObj).filter_by(phoneSeg = callPhoneSeg).first()
                callPhoneCity = callPhoneInfo.cityID
            else:
                callPhoneSeg = callPhone[0:4]
                callPhoneInfo = session.query(phoneSegObj).filter_by(phoneSeg = callPhoneSeg).first()
                callPhoneCity = callPhoneInfo.cityID
        except:
            return ipList
            
        if localPhoneCity == callPhoneCity:
            return ipList
        else:
            isOrderInfo = session.query(skyUserVOIPOrderObj).filter_by(userID = userInfo.userID).first()
            if isOrderInfo == None:
               transaction=session.create_transaction()
               try: 
                   isOrderInfo = skyUserVOIPOrderObj()
                   isOrderInfo.userID = userInfo.userID
                   isOrderInfo.isOrder = 0
                   session.save(isOrderInfo)
                   VOIPInfoList = session.query(VOIPInfoObj).filter_by(phoneProvider = localPhoneProvider).all()
                   for i in range(len(VOIPInfoList)):
                       userVOIP = skyUserVOIPObj()
                       userVOIP.userID = userInfo.userID
                       userVOIP.voipID = i
                       userVOIP.voipIndex = VOIPInfoList[i].voipIndex
                       session.query(skyUserVOIPObj)
                       session.save(userVOIP)
                   transaction.commit()
               except:
                    transaction.rollback()
                    raise
                
            if isOrderInfo.isOrder == 0:
                UserVOIPList = session.query(skyUserVOIPObj).filter_by(userID = userInfo.userID).all()#按频率排�序                
                for UserVOIPItem in UserVOIPList:
                    VOIPItem = session.query(VOIPInfoObj).filter_by(voipIndex = UserVOIPItem.voipIndex).first()
                    ipList.append([VOIPItem.voip, VOIPItem.remark])
            else:
                UserVOIPList = session.query(skyUserVOIPObj).filter_by(userID = userInfo.userID).all()#按voipID排序
                for UserVOIPItem in UserVOIPList:
                    VOIPItem = session.query(VOIPInfoObj).filter_by(voipIndex = UserVOIPItem.voipIndex).first()
                    ipList.append([VOIPItem.voip, VOIPItem.remark])
            
        return ipList
    
    def getVOIPInfo(self):
        ipList = []
        session = sqlalchemy.orm.create_session()
        userInfo = session.query(skyUserInfoObj).filter_by(accounts = self.id_).first()
        
        isOrderInfo = session.query(skyUserVOIPOrderObj).filter_by(userID = userInfo.userID).first()
        if isOrderInfo == None:
            userPhoneList = session.query(skyUserPhoneObj).filter_by(userID = userInfo.userID).all()
            if len(userPhoneList) == 0:
                error = "user is not in the table(skyUserInfoObj)"
                raise error
            
            localPhone = userPhoneList[0].phoneNum

            localPhoneSeg = localPhone[0:7]
            localPhoneInfo = session.query(phoneSegObj).filter_by(phoneSeg = localPhoneSeg).first()
            localPhoneProvider = localPhoneInfo.phoneProvider
            
            transaction=session.create_transaction()
            try: 
                isOrderInfo = skyUserVOIPOrderObj()
                isOrderInfo.userID = userInfo.userID
                isOrderInfo.isOrder = 0
                session.save(isOrderInfo)
                VOIPInfoList = session.query(VOIPInfoObj).filter_by(phoneProvider = localPhoneProvider).all()
                for i in range(len(VOIPInfoList)):
                    userVOIP = skyUserVOIPObj()
                    userVOIP.userID = userInfo.userID
                    userVOIP.voipID = i
                    userVOIP.voipIndex = VOIPInfoList[i].voipIndex
                    session.query(skyUserVOIPObj)
                    session.save(userVOIP)
                transaction.commit()
            except:
                transaction.rollback()
                raise
            
        UserVOIPList = session.query(skyUserVOIPObj).filter_by(userID = userInfo.userID).all()#按voipID排序
        for UserVOIPItem in UserVOIPList:
            VOIPItem = session.query(VOIPInfoObj).filter_by(voipIndex = UserVOIPItem.voipIndex).first()
            ipList.append([VOIPItem.voip, VOIPItem.remark])
            
        return isOrderInfo.isOrder, ipList
    
    def setVOIPInfo(self, isOrder, ipList):
        session = sqlalchemy.orm.create_session()
        userInfo = session.query(skyUserInfoObj).filter_by(accounts = self.id_).first()
        transaction=session.create_transaction()
        try:
            isOrderInfo = session.query(skyUserVOIPOrderObj).filter_by(userID = userInfo.userID).first()
            if isOrderInfo == None:
                isOrderInfo = skyUserVOIPOrderObj()
                isOrderInfo.userID = userInfo.userID
                isOrderInfo.isOrder = isOrder
                session.save(isOrderInfo)
            else:
                isOrderInfo.isOrder = isOrder
                session.save(isOrderInfo)
            
            VOIPMap = {}
            UserVOIPList = session.query(skyUserVOIPObj).filter_by(userID = userInfo.userID).all()
            for UserVOIPItem in UserVOIPList:
                VOIPMap[UserVOIPItem.voipIndex] = UserVOIPItem.touchFrequency
                session.delete(UserVOIPItem)
                session.flush()
            
            for i in range(len(ipList)):
                VOIPItem = session.query(VOIPInfoObj).filter_by(voip = ipList[i][0]).first()
                if VOIPItem == None:
                    VOIPInfo = VOIPInfoObj()
                    VOIPInfo.voip = ipList[i][0]
                    VOIPInfo.remark = ipList[i][1]
                    session.save(VOIPInfo)
                    session.flush()
                    VOIPItem = session.query(VOIPInfoObj).filter_by(voip = ipList[i][0]).first()
                    
                userVOIP = skyUserVOIPObj()
                userVOIP.userID = userInfo.userID
                userVOIP.voipID = i
                userVOIP.voipIndex = VOIPItem.voipIndex
                userVOIP.touchFrequency = VOIPMap.get(VOIPItem.voipIndex, 0)
                session.query(skyUserVOIPObj)
                session.save(userVOIP)
            
            transaction.commit()
        except:
            transaction.rollback()
            raise
        
        return True
    
    def beginExport(self):
        print "\nbeginExport()\n"
        self.session = sqlalchemy.orm.create_session() 
        user = self.session.query(skyUserInfoObj).filter_by(accounts = self.id_).first()
        if user == None:
            error = "user is not in the table(skyUserInfoObj)"
            raise error
        
        self.transaction = self.session.create_transaction()
        try:
            localFriendList = self.session.query(LocalUserInfoObj).filter_by(skyUserID = user.userID).all()
            for localFriend in localFriendList:
                localFriendSceneList = self.session.query(skySceneObj).filter_by(userID = localFriend.userID).all()
                for localFriendScene in localFriendSceneList :
                    localFriendScene_bak1 = skySceneObj_bak1(localFriendScene)
                    self.session.query(skySceneObj_bak1)
                    self.session.save(localFriendScene_bak1)
                    self.session.query(skySceneObj)
                    self.session.delete(localFriendScene)
                    self.session.flush()
                userPhoneList = self.session.query(skyUserPhoneObj).filter_by(userID = localFriend.userID).all()
                for userPhone in userPhoneList :
                    userPhone_bak1 = skyUserPhoneObj_bak1(userPhone)
                    self.session.query(skyUserPhoneObj_bak1)
                    self.session.save(userPhone_bak1)
                    self.session.query(skyUserPhoneObj)
                    self.session.delete(userPhone)
                    self.session.flush()
                   
                localFriend_bak1 = LocalUserInfoObj_bak1(localFriend)
                self.session.query(LocalUserInfoObj_bak1)
                self.session.save(localFriend_bak1)
                self.session.query(LocalUserInfoObj)
                self.session.delete(localFriend)
                self.session.flush()
        except:
            self.transaction.rollback()
            raise
        
        self.timer = threading.Timer(30.0, self.rollback)
        self.timer.start()
        
        print "\nend beginExport()\n"
        return True
    
    def endExport(self):
        print "\nendExport()\n"
        self.timer.cancel()
        self.transaction.commit()
        self.transaction = None
        print "\nend endExport()\n"
        return True
    
    def rollback(self):
        print "\nrollback()\n"
        self.timer.cancel()
        self.transaction.rollback()
        self.transaction = None
        print "\nend rollback()\n"
        return True
    
    def export(self, contacts):
        print "\nexport()\n"
#        if self.transaction == None:
#            error = "time out"
#            raise error
#        
        self.session = sqlalchemy.orm.create_session() 
        
        user = self.session.query(skyUserInfoObj).filter_by(accounts = self.id_).first()
        if user == None:
            error = "user is not in the table(skyUserInfoObj)"
            raise error
        self.transaction = self.session.create_transaction()
        
        formattedAddr = ""
        addr = ""
        name = ""
        formattedName = ""
        nickName = ""
        account = ""
        
        try: 
            for contact in contacts:
                localFriend = LocalUserInfoObj()
                localFriendPhone = skyUserPhoneObj()
                localFriendScene = skySceneObj()
                localFriend.skyUserID = user.userID
                localFriend.searchmsg = ""
                for contactField in contact:
                    if contactField[0] == 100:
                        addr = contactField[3][6] + contactField[3][4] + contactField[3][3] + contactField[3][2]
                    if contactField[0] == 104:
                        formattedAddr = contactField[3][0]
                    if contactField[0] == 105: 
                        formattedName = contactField[3][0]
                    if contactField[0] == 106:
                        name = contactField[3][0] + contactField[3][1]    
                    if contactField[0] == 107:
                        nickName = contactField[3][0]
                    if contactField[0] == 115:
                        phoneNum = contactField[3][0]
                        localFriendPhone.phoneNum = phoneNum
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriendPhone.phoneNum
                    if contactField[0] == 103:
                        email = contactField[3][0]
                        localFriend.email = email
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.email
                    if contactField[0] == 118:
                        url = contactField[3][0]
                        localFriend.myUrl = url
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.myUrl
                    if contactField[0] == 108:
                        remark = contactField[3][0]
                        localFriend.remark = remark
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.remark
                    if contactField[0] == 110:
                        photo = contactField[3][0]
                        localFriend.myPhoto = photo
                    if contactField[0] == 117:
                        uid = contactField[3][0]
                        localFriend.uid = uid
                        
                if formattedAddr != "":
                    localFriend.address = formattedAddr
                else:
                    localFriend.address = addr
                localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.address
                        
                if formattedName != "":
                    localFriend.nickName = formattedName
                    account = formattedName
                    localFriendScene.sceneName = formattedName
                elif name != "":
                    localFriend.nickName = name
                    account = name
                    localFriendScene.sceneName = name
                else:
                    localFriend.nickName = nickName
                    account = nickName
                    localFriendScene.sceneName = nickName
                localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.nickName
                    
                localFriendList = self.session.query(LocalUserInfoObj).filter_by(nickName = account, skyUserID = user.userID).all()
                account = "_" + account + str(len(localFriendList))
                localFriend.accounts = account
                
                print localFriend.searchmsg              
                    
                self.session.query(LocalUserInfoObj)
                self.session.save(localFriend)
                self.session.flush()
                localFriend = self.session.query(LocalUserInfoObj).filter_by(accounts = account, skyUserID = user.userID).first()
                localFriendPhone.userID = localFriend.userID
                localFriendPhone.phoneIndex = 0
                self.session.query(skyUserPhoneObj)
                self.session.save(localFriendPhone)
                self.session.flush()
                
                localFriendScene.userID = localFriend.userID
                localFriendScene.sceneID = 0
                localFriendScene.phoneIndex = 0
                localFriendScene.touchFrequency = 0
                self.session.query(skySceneObj)
                self.session.save(localFriendScene)
                self.session.flush()

            self.transaction.commit()
        except:
            self.transaction.rollback()
            raise
        
        print "\nEnd export()\n"
        return True

class SkySecManager():
    def __init__(self):
        pass
    def logIn(self, id, pwd):
        print "\nlogIn()\n"
        session = sqlalchemy.orm.create_session()
        result = session.query(skyUserInfoObj).filter_by(accounts = id, password = pwd)
        if result is None:
            error = "user is not in the table(skyUserPhoneObj)"
            raise error
        print result
        print "\nEnd logIn()\n"
        return True

    def signIn(self, info):  
        print "\nsignIn()\n"  
        session = sqlalchemy.orm.create_session()
        result = session.query(skyUserInfoObj).filter_by(accounts = info.account).first()
        if result != None :
            error = "user is in the table(skyUserPhoneObj)"
            raise error
            
        user_info = skyUserInfoObj()
        user_info.accounts = info.account
        if info.nickname == '':
            user_info.nickName = info.account
        else:
            user_info.nickName = info.nickname
        user_info.searchmsg = user_info.searchmsg + "-" + user_info.nickName
        user_info.sceneID = 0
        user_info.password = info.password
        user_info.modifyTime = 0
        session.save(user_info)
        session.flush()   
        
        print "\nEnd signIn()\n"  
        return True
    
    def check(self, id):
        print locals()
        return True

    def getCode(self, id):
        print locals()
        return True 

class ThreadingServer(ThreadingMixIn, SimpleXMLRPCServer):
    """ 这个类是简单的继承ThreadingMixIn, SimpleXMLRPCServer类，实现其功�?"""
    pass

#class Server():
#    def __init__(self):
#        self.skyUserInfoTable = None
#        self.skyUserRelationTable = None
#        self.skySceneTable = None
#        self.skySceneTable_bak1 = None
#        self.LocalUserInfoTable = None
#        self.LocalUserInfoTable_bak1 = None
#        self.skyUserPhoneTable = None
#        self.skyUserPhoneTable_bak1 = None
#    def run(self):
dbengine = sqlalchemy.create_engine(g_DBConnectionStr, echo=False, auto_identity_insert = False)
meta = sqlalchemy.MetaData(dbengine)
skyUserInfoTable = sqlalchemy.Table('skyUserInfo', meta
                                    , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                    , sqlalchemy.Column('accounts', String(20))
                                    , sqlalchemy.Column('password', String(8))
                                    , sqlalchemy.Column('nickName', String(50))
                                    , sqlalchemy.Column('email', String(50))
                                    , sqlalchemy.Column('address', String(100))
                                    , sqlalchemy.Column('myUrl', String(50))
                                    , sqlalchemy.Column('myPhoto', String())
                                    , sqlalchemy.Column('imTool', String(50))
                                    , sqlalchemy.Column('sceneID', Integer, primary_key = False, autoincrement=False)
                                    , sqlalchemy.Column('totalFrequency', Integer, primary_key = False, autoincrement=False)
                                    , sqlalchemy.Column('remark', String(100))
                                    , sqlalchemy.Column('searchmsg', String(300))
                                    , sqlalchemy.Column('modifyTime', Integer, primary_key = False, autoincrement=False))
skyUserRelationTable = sqlalchemy.Table('skyUserRelation', meta
                                        , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                        , sqlalchemy.Column('friendID', Integer, primary_key = True, autoincrement=False)
                                        , sqlalchemy.Column('friendNickName', String(50))
                                        , sqlalchemy.Column('friendSceneID', Integer, primary_key = False, autoincrement=False))
skySceneTable = sqlalchemy.Table('skyScene', meta
                                , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                , sqlalchemy.Column('sceneID', Integer, primary_key = True, autoincrement=False)
                                , sqlalchemy.Column('phoneIndex', Integer, primary_key = False, autoincrement=False)
                                , sqlalchemy.Column('sceneName', String(50))
                                , sqlalchemy.Column('touchFrequency', Integer, primary_key = False, autoincrement=False))
skySceneTable_bak1 = sqlalchemy.Table('skyScene_bak1', meta
                                    , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                    , sqlalchemy.Column('sceneID', Integer, primary_key = True, autoincrement=False)
                                    , sqlalchemy.Column('phoneIndex', Integer, primary_key = False, autoincrement=False)
                                    , sqlalchemy.Column('sceneName', String(50))
                                    , sqlalchemy.Column('touchFrequency', Integer, primary_key = False, autoincrement=False))
LocalUserInfoTable = sqlalchemy.Table('LocalUserInfo', meta
                                    , sqlalchemy.Column('skyUserID', Integer, primary_key = False, autoincrement=False)
                                    , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                    , sqlalchemy.Column('accounts', String(20))
                                    , sqlalchemy.Column('password', String(8))
                                    , sqlalchemy.Column('nickName', String(50))
                                    , sqlalchemy.Column('email', String(50))
                                    , sqlalchemy.Column('address', String(100))
                                    , sqlalchemy.Column('myUrl', String(50))
                                    , sqlalchemy.Column('myPhoto', String())
                                    , sqlalchemy.Column('imTool', String(50))
                                    , sqlalchemy.Column('sceneID', Integer, primary_key = False, autoincrement=False)
                                    , sqlalchemy.Column('totalFrequency', Integer, primary_key = False, autoincrement=False)
                                    , sqlalchemy.Column('remark', String(100))
                                    , sqlalchemy.Column('searchmsg', String(300))
                                            , sqlalchemy.Column('modifyTime', Integer, primary_key = False, autoincrement=False)
                                            , sqlalchemy.Column('uid', String(15)))
LocalUserInfoTable_bak1 = sqlalchemy.Table('LocalUserInfo_bak1', meta
                                        , sqlalchemy.Column('skyUserID', Integer, primary_key = False, autoincrement=False)
                                        , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                        , sqlalchemy.Column('accounts', String(20))
                                        , sqlalchemy.Column('password', String(8))
                                        , sqlalchemy.Column('nickName', String(50))
                                        , sqlalchemy.Column('email', String(50))
                                        , sqlalchemy.Column('address', String(100))
                                        , sqlalchemy.Column('myUrl', String(50))
                                        , sqlalchemy.Column('myPhoto', String())
                                        , sqlalchemy.Column('imTool', String(50))
                                        , sqlalchemy.Column('sceneID', Integer, primary_key = False, autoincrement=False)
                                        , sqlalchemy.Column('totalFrequency', Integer, primary_key = False, autoincrement=False)
                                        , sqlalchemy.Column('remark', String(100))
                                        , sqlalchemy.Column('searchmsg', String(300))
                                                , sqlalchemy.Column('modifyTime', Integer, primary_key = False, autoincrement=False)
                                                , sqlalchemy.Column('uid', String(15)))
skyUserPhoneTable = sqlalchemy.Table('skyUserPhone', meta
                                    , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                    , sqlalchemy.Column('phoneIndex', Integer, primary_key = True, autoincrement=False)
                                    , sqlalchemy.Column('phoneNum', String(20))
                                    , sqlalchemy.Column('description', String(50)))
skyUserPhoneTable_bak1 = sqlalchemy.Table('skyUserPhone_bak1', meta
                                        , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                        , sqlalchemy.Column('phoneIndex', Integer, primary_key = True, autoincrement=False)
                                        , sqlalchemy.Column('phoneNum', String(20))
                                        , sqlalchemy.Column('description', String(50)))

total_table = sqlalchemy.Table('TotalTable', meta,
     sqlalchemy.Column('Total', Integer, primary_key=True) )

skyUserVOIPTable = sqlalchemy.Table('skyUserVOIP', meta
                                    , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                    , sqlalchemy.Column('voipID', Integer, primary_key = True, autoincrement=False)
                                    , sqlalchemy.Column('voipIndex', Integer, primary_key = False, autoincrement=False)
                                    , sqlalchemy.Column('touchFrequency', Integer, primary_key = False, autoincrement=False))
skyUserVOIPOrderTable = sqlalchemy.Table('skyUserVOIPOrder', meta
                                        , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                        , sqlalchemy.Column('isOrder', Integer, primary_key = False, autoincrement=False))
VOIPInfoTable = sqlalchemy.Table('VOIPInfo', meta
                                , sqlalchemy.Column('voipIndex', Integer, primary_key = True, autoincrement=False)
                                , sqlalchemy.Column('voip', String(20))
                                , sqlalchemy.Column('remark', String(50))
                                , sqlalchemy.Column('touchFrequency', Integer, primary_key = False, autoincrement=False)
                                , sqlalchemy.Column('phoneProvider', Integer, primary_key = False, autoincrement=False))
phoneSegTable = sqlalchemy.Table('phoneSeg', meta
                                , sqlalchemy.Column('phoneSeg', String(20), primary_key = True, autoincrement=False)
                                , sqlalchemy.Column('provinceID', Integer, primary_key = False, autoincrement=False)
                                , sqlalchemy.Column('cityID', Integer, primary_key = False, autoincrement=False)
                                , sqlalchemy.Column('phoneProvider', Integer, primary_key = False, autoincrement=False))

sqlalchemy.orm.mapper(skyTotalUserCountObj, total_table)
sqlalchemy.orm.mapper(skyUserPhoneObj, skyUserPhoneTable)
sqlalchemy.orm.mapper(skyUserPhoneObj_bak1, skyUserPhoneTable_bak1)
sqlalchemy.orm.mapper(skyUserRelationObj, skyUserRelationTable)
sqlalchemy.orm.mapper(skySceneObj, skySceneTable)
sqlalchemy.orm.mapper(skySceneObj_bak1, skySceneTable_bak1)
sqlalchemy.orm.mapper(skyUserInfoObj, skyUserInfoTable)
sqlalchemy.orm.mapper(LocalUserInfoObj, LocalUserInfoTable) 
sqlalchemy.orm.mapper(LocalUserInfoObj_bak1, LocalUserInfoTable_bak1) 
sqlalchemy.orm.mapper(skyUserVOIPObj, skyUserVOIPTable)
sqlalchemy.orm.mapper(skyUserVOIPOrderObj, skyUserVOIPOrderTable) 
sqlalchemy.orm.mapper(VOIPInfoObj, VOIPInfoTable) 
sqlalchemy.orm.mapper(phoneSegObj, phoneSegTable)

        
if __name__ == "__main__":
#    meta.create_all()
    mgr = SkySecManager()
    mgr.logIn('skyUser5', '123456')
    pim = SkyPimManager('skyUser5').find('skyUse', 1, 10, 0)
#    pim.export(contacts) 
#    contacts = []
#    contact = []
#    contact2 = []
#    
#    Field_nickname = contactField()
#    Field_nickname.fieldID = 106
#    Field_nickname.attrValueArray.append("xie")
#    Field_nickname.attrValueArray.append("haiping")
#    contact.append(Field_nickname)
#    
#    Field_addr = contactField()
#    Field_addr.fieldID = 104
#    Field_addr.attrValueArray.append("jiangxi fuzhou pengtian")
#    contact.append(Field_addr)
#    
#    Field_phone = contactField()
#    Field_phone.fieldID = 115
#    Field_phone.attrValueArray.append("13480737672")
#    contact.append(Field_phone)
#    
#    Field_email = contactField()
#    Field_email.fieldID = 103
#    Field_email.attrValueArray.append("64happy@gmail.com")
#    contact.append(Field_email)
#    
#    Field_url = contactField()
#    Field_url.fieldID = 118
#    Field_url.attrValueArray.append("www.sina.com.cn")
#    contact.append(Field_url)
#    
#    Field_remark = contactField()
#    Field_remark.fieldID = 108
#    Field_remark.attrValueArray.append("helloworld")
#    contact.append(Field_remark)
#    
#    contacts.append(contact)
#    
#    
#    Field_nickname2 = contactField()
#    Field_nickname2.fieldID = 106
#    Field_nickname2.attrValueArray.append("xu")
#    Field_nickname2.attrValueArray.append("hong")
#    contact2.append(Field_nickname2)
#    
#    Field_addr2 = contactField()
#    Field_addr2.fieldID = 104
#    Field_addr2.attrValueArray.append("shichuang luzhou")
#    contact2.append(Field_addr2)
#    
#    Field_phone2 = contactField()
#    Field_phone2.fieldID = 115
#    Field_phone2.attrValueArray.append("13411111111")
#    contact2.append(Field_phone2)
#    
#    Field_email2 = contactField()
#    Field_email2.fieldID = 103
#    Field_email2.attrValueArray.append("xuhong@gmail.com")
#    contact2.append(Field_email2)
#    
#    Field_url2 = contactField()
#    Field_url2.fieldID = 118
#    Field_url2.attrValueArray.append("www.sohu.com.cn")
#    contact2.append(Field_url2)
#    
#    Field_remark2 = contactField()
#    Field_remark2.fieldID = 108
#    Field_remark2.attrValueArray.append("hellotmd")
#    contact2.append(Field_remark2)
#    
#    contacts.append(contact2)
#    
#    pim = SkyPimManager("xhp")
#    pim.export(contacts)     